package com.banciyuan.bcywebview.biz.goods.store;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.base.view.space.Space;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailGoods;

/**
 * Created by squall on 2016/11/3.
 */

public class AllGoodsFragment extends BaseLazyContainerFragment {

    private int page = 1;
    private int type=0;
    private boolean is_load;
    private boolean is_end;
    private AllGoodsAdapter allGoodsAdapter;
    private List<DetailGoods> dlist = new ArrayList<>();
    private PullToRefreshListView refreshListView;
    private ListView mListView;

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewroot=inflater.inflate(R.layout.not_login_discover,null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initUi(View rootview) {
        refreshListView= (PullToRefreshListView) rootview.findViewById(R.id.refreshview);
        mListView=refreshListView.getRefreshableView();
        Space space=new Space(getActivity());
        AbsListView.LayoutParams params=new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, UIUtils.dip2px(8,getActivity()));
        space.setLayoutParams(params);
        space.setBackgroundColor(getResources().getColor(R.color.background));
        mListView.addHeaderView(space);
    }

    @Override
    protected void initAction() {
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_end=false;
                is_load=false;
                page=1;
                initData();
            }
        });

        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(!is_end&&!is_load){
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initProgressbar(View viewroot) {
        mProgressbarView = viewroot.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        type=getArguments().getInt("type");
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getAllHotGoods();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.ZPID, type + ""));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject=new JSONObject(response);
                        Gson gson=new Gson();
                        List<DetailGoods> templist= gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA),new TypeToken<List<DetailGoods>>(){}.getType());
                        renderData(templist);
                    }else{
                        mProgressbarHelper.onFailed();
                        refreshListView.onRefreshComplete();
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                    refreshListView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
                refreshListView.onRefreshComplete();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private void renderData(List<DetailGoods> templist) {
        if(page==1){
            dlist.clear();
        }
        dlist.addAll(templist);
        if(templist.isEmpty()){
            is_end=true;
        }
        if(allGoodsAdapter==null){
            allGoodsAdapter=new AllGoodsAdapter(dlist,getActivity());
            mListView.setAdapter(allGoodsAdapter);
        }else{
            allGoodsAdapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
    }
}
